package com.lsh.payment.core.service.refund;

import com.lsh.base.common.exception.BusinessException;
import com.lsh.payment.core.model.payenum.RefundStatus;
import com.lsh.payment.core.model.refund.PayRefund;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

/**
 * Project Name: lsh-payment
 *
 * @author peter
 * @date 18/6/2
 * 北京链商电子商务有限公司
 * Package
 * desc:
 */
public abstract class AbstractRefundOrderStatusService implements IRefundOrderStatusService {

    @Autowired
    private PayRefundOrderService payRefundOrderService;

    @Transactional(rollbackFor = RuntimeException.class)
    @Override
    public boolean modifyStatus(PayRefund payRefund, boolean addJopFlag) {

        RefundStatus target = this.getTargetStatus();

        if (!this.validate(payRefund, target)) {
            return false;
        }

        this.beforeProcess(payRefund);

        this.payRefundOrderService.updateRefundStatus(this.orderRefund4update(payRefund, target));

        this.afterProcess(payRefund, addJopFlag);

        return true;
    }

    protected PayRefund defaultPayRefund(PayRefund payRefund, RefundStatus target) {

        PayRefund payRefund4update = new PayRefund();
        payRefund4update.setPaymentRefundNo(payRefund.getPaymentRefundNo());
        payRefund4update.setChannelRefundId(payRefund.getChannelRefundId());
        payRefund4update.setRefundStatus(target.getValue());
        payRefund4update.setExt(payRefund.getExt());

        return payRefund4update;
    }

    /**
     * 校验处理
     * @param payRefund    当前退款对象
     * @param target       目标退款记录状态对象
     * @return             校验结果
     */
    protected abstract boolean validate(PayRefund payRefund, RefundStatus target);

    /**
     * 状态流转前置处理
     * @param payRefund             单签退款对象
     * @return                      处理标识
     * @throws BusinessException    业务异常
     */
    protected abstract boolean beforeProcess(PayRefund payRefund) throws BusinessException;

    /**
     * 构建状态流转退款对象
     * @param payRefund            当前退款对象
     * @param target               目标退款记录状态对象
     * @return PayRefund           修改对象
     * @throws BusinessException   业务异常
     */
    protected abstract PayRefund orderRefund4update(PayRefund payRefund, RefundStatus target) throws BusinessException;

    /**
     * 状态流转后置处理
     * @param payRefund             当前退款对象
     * @param addJopFlag            添加后置任务标记
     * @return                      处理结果标识
     * @throws BusinessException    业务异常
     */
    protected abstract boolean afterProcess(PayRefund payRefund, boolean addJopFlag) throws BusinessException;

}
